package com.ktwlsoft.archivemanage.domain.business.businessService.guiBusiness;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.businessService.AccountManageService;
import com.ktwlsoft.archivemanage.domain.business.businessService.BasisBusinessManageService;
import com.ktwlsoft.archivemanage.domain.business.businessService.ImgUploadService;
import com.ktwlsoft.archivemanage.domain.business.businessService.NotifyMessageScheduleTask;
import com.ktwlsoft.archivemanage.domain.business.businessService.businessInspect.BusinessSelfOrRepeatInspectService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.UnitMemberRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuiBusinessGuidanceRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuiGuidanceItemRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuidanceApplyRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiBusinessGuidance;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiGuidanceItem;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiGuidanceMendList;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuidanceApply;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessGuidance.*;
import com.ktwlsoft.archivemanage.payload.guiBusiness.BasisBusinessManageRequest;
import com.ktwlsoft.archivemanage.payload.guiBusiness.CommitRequest;
import com.ktwlsoft.archivemanage.payload.guiBusiness.GuiBusinessPageRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import com.ktwlsoft.archivemanage.service.utils.StringUtil;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 业务指导
 *
 * @author zhuhe on 2020/3/12 14:12
 * @version 1.0
 */
@Service
public class BusinessGuidanceService {

    /**
     * 业务指导
     */
    @Getter
    private final GuiBusinessGuidanceRepositoryService repositoryService;

    /**
     * 指导条目
     */
    private final GuiGuidanceItemRepositoryService itemRepositoryService;

    private final NotifyMessageScheduleTask notifyMessageScheduleTask;
    private final UnitMemberRepositoryService memberRepositoryService;
    /**
     * 图片保存
     */
    private final ImgsService imgsService;

    /**
     * 指导申请
     */
    private final GuidanceApplyRepositoryService applyRepositoryService;

    /**
     * 整改单
     */
    private final GuiGuidanceMendListService mendListService;

    /**
     * 依据业务管理
     */
    private final BasisBusinessManageService basisBusinessManageService;

    /**
     * 账号管理
     */
    private final AccountRepositoryService accountRepositoryService;
    private final BusinessSelfOrRepeatInspectService businessInspectService;


    public BusinessGuidanceService(BusinessSelfOrRepeatInspectService businessInspectService, UnitMemberRepositoryService memberRepositoryService, GuiBusinessGuidanceRepositoryService repositoryService, GuiGuidanceItemRepositoryService itemRepositoryService, NotifyMessageScheduleTask notifyMessageScheduleTask, ImgsService imgsService, GuidanceApplyRepositoryService applyRepositoryService, GuiGuidanceMendListService mendListService, BasisBusinessManageService basisBusinessManageService, AccountManageService accountManageService, AccountRepositoryService accountRepositoryService) {
        this.repositoryService = repositoryService;
        this.itemRepositoryService = itemRepositoryService;
        this.notifyMessageScheduleTask = notifyMessageScheduleTask;
        this.imgsService = imgsService;
        this.applyRepositoryService = applyRepositoryService;
        this.mendListService = mendListService;
        this.basisBusinessManageService = basisBusinessManageService;
        this.accountRepositoryService = accountRepositoryService;
        this.memberRepositoryService = memberRepositoryService;
        this.businessInspectService = businessInspectService;
    }

    /**
     * 业务指导保存
     *
     * @param request
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(BusinessGuidanceSaveRequest request) {

        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            account = new Account();
        }
        String name = PinyinUtil.getFirstLetter(Optional.ofNullable(account.getRealName()).orElse("yx"), "");
        List<Long> list = Lists.newArrayList();
        for (BusinessGuidanceUnit unit : request.getUnit()) {
            GuiBusinessGuidance businessGuidance = new GuiBusinessGuidance();
            UnitMember unitMember = memberRepositoryService.getByUnitId(unit.getUnitId());
            BeanUtils.copyProperties(request, businessGuidance);
            //设置立档单位信息
            businessGuidance.setUnit(unit.getUnit());
            businessGuidance.setUnitLocation(unit.getUnitLocation());
            businessGuidance.setUnitId(unit.getUnitId());
            //设置档案员信息
            businessGuidance.setArchievist(unitMember.getRecorder());
            businessGuidance.setArchievistId(unitMember.getRecorderId());
            if (unitMember.getRecorderTele() != null && !unitMember.getRecorderTele().isEmpty()) {
                businessGuidance.setArchievistPhone(Long.parseLong(unitMember.getRecorderTele()));
            }

            //指导单号
            String s = "";
            Result<?> mount = getRecorderMount(account.getId());
            String year = DateUtil.format(new Date(), DatePattern.NORM_YEAR_PATTERN);
            String mo = ObjectUtil.isNotEmpty(mount.getData()) ? mount.getData().toString() : "";
            String num = StrUtil.isNotBlank(mo) && !"0".equals(mo) ? mo.substring(4) : "000";
            String num2 = String.valueOf(Integer.parseInt(num) + 1);
            s += name;
            s += year;
            for (int i1 = num2.length(); i1 < num.length(); i1++) {
                s += "0";
            }
            s += num2;
            businessGuidance.setGuidanceNum(s);

            if (request.getAdviceImgSign() != null) {
                businessGuidance.setAdviceImgSign(String.valueOf(imgsService.save(businessGuidance.getId(), "ADVICESIGN", request.getAdviceImgSign().getUrl())));
            } else {
                businessGuidance.setAdviceImgSign("0");
            }
            if (request.getGuideAdviceSign() != null) {
                businessGuidance.setGuideAdviceSign(String.valueOf(imgsService.save(businessGuidance.getId(), "BYGUIDESIGN", request.getGuideAdviceSign().getUrl())));
            } else {
                businessGuidance.setGuideAdviceSign("0");
            }

            businessGuidance.setCreatedAt(new Date());
            businessGuidance.setGuideAt(new Date());
            businessGuidance.setDataState(1);
            businessGuidance.setCreator(account.getRealName());
            businessGuidance.setCreatorId(account.getId());
            businessGuidance.setInstructorName(account.getRealName());
            businessGuidance.setInstructorId(account.getId());
            businessGuidance.setGuideAt(new Date());
            //条目
            List<GuiGuidanceItem> itemList = Lists.newArrayList();
            //依据
            List<BasisBusinessManage> manageList = Lists.newArrayList();
            if (request.getItemList() != null && request.getItemList().size() > 0) {
                for (GuiGuidanceItemUpdateRequest value : request.getItemList()) {
                    GuiGuidanceItem guidanceItem = new GuiGuidanceItem();
                    BeanUtils.copyProperties(value, guidanceItem);
                    guidanceItem.setGuidanceId(businessGuidance.getId());
                    guidanceItem.setDataState(1);
                    guidanceItem.setId(SnowFlake.getNextId());
                    itemList.add(guidanceItem);
                    if (value.getImgList() != null && value.getImgList().size() > 0) {
                        imgsService.manySave(guidanceItem.getId(), "GUIDEITEMIMG", value.getImgList());
                    }
                    //依据
                    if (value.getBasisBusinessManages() != null) {
                        for (BasisBusinessManageRequest basis : value.getBasisBusinessManages()) {
                            basis.setId(SnowFlake.getNextId());
                            basis.setBusinessId(guidanceItem.getId());
                            basis.setBasisType("default");
                            basis.setCreateId(account.getId());
                            basis.setCreateName(account.getRealName());
                            basis.setCreateTime(new Date());
                            BasisBusinessManage manage = BasisBusinessManage.builder().build();
                            BeanUtils.copyProperties(basis, manage);
                            try {
                                manage.setContent(basis.getContent().getBytes("UTF-8"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            manageList.add(manage);
                        }
                    }
                }
            }
            try {
                repositoryService.insert(businessGuidance);
                if (!itemList.isEmpty()) {
                    itemRepositoryService.manyInsert(itemList);
                }
                if (!manageList.isEmpty()) {
                    basisBusinessManageService.getRepositoryService().manyInsert(manageList);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new ResultException(ResultType.SAVING_ERROR.getReason(), ResultType.SAVING_ERROR);
            }
            //更新指导申请
            if (businessGuidance.getApplyNum() != null && !"".equals(businessGuidance.getApplyNum())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("applyNum", businessGuidance.getApplyNum());
                List<GuidanceApply> applyList = applyRepositoryService.findList(jsonObject);
                if (applyList != null && applyList.size() > 0) {
                    applyList.get(0).setGuidanceNum(businessGuidance.getGuidanceNum());
                    applyList.get(0).setState(5);
                    try {
                        applyRepositoryService.update(applyList.get(0));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            list.add(businessGuidance.getId());
            saveLog(OperationLog.OperationType.ADD, (account.getRealName() != null ? account.getRealName() : "") + "为\"" + unit.getUnit() + "\"添加了业务指导,指导单号:" + businessGuidance.getGuidanceNum());

        }

        return Result.ok(list);
    }

    /**
     * 业务指导更新
     *
     * @param request
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update(BusinessGuidanceUpdateRequest request) {
        if (!"STAGE".equals(request.getState())) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("非暂存状态不可编辑");
        }
        GuiBusinessGuidance businessGuidance = new GuiBusinessGuidance();
        BeanUtils.copyProperties(request, businessGuidance);
        businessGuidance.setId(Long.parseLong(request.getId()));
        List<GuiBusinessGuidance> guidances = repositoryService.getByGuidanceNum(request.getGuidanceNum());
        if (guidances != null && guidances.size() > 0) {
            for (GuiBusinessGuidance guidance : guidances) {
                if (!guidance.getId().equals(Long.parseLong(request.getId()))) {
                    return Result.body(null, ResultType.CHECK_ERROR).withMessage("指导单号重复");
                }
            }
        }
        // 处理签名图片
        if (request.getAdviceImgSign() != null) {
            businessGuidance.setAdviceImgSign(String.valueOf(imgsService.save(businessGuidance.getId(), "ADVICESIGN", request.getAdviceImgSign().getUrl())));
        }
        if (request.getGuideAdviceSign() != null) {
            businessGuidance.setGuideAdviceSign(String.valueOf(imgsService.save(businessGuidance.getId(), "BYGUIDESIGN", request.getGuideAdviceSign().getUrl())));
        }
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            account = new Account();
        }
        businessGuidance.setGuideAt(new Date());
        try {
            if (request.getItemList() != null && request.getItemList().size() > 0) {
                for (GuiGuidanceItemUpdateRequest value : request.getItemList()) {
                    GuiGuidanceItem guidanceItem = new GuiGuidanceItem();
                    BeanUtils.copyProperties(value, guidanceItem);
                    if (value.getType() != null && value.getType().equals(1)) {
                        guidanceItem.setGuidanceId(businessGuidance.getId());
                        guidanceItem.setDataState(1);
                        itemRepositoryService.insert(guidanceItem);
                        imgsService.manySave(guidanceItem.getId(), "GUIDEITEMIMG", value.getImgList());
                        //处理依据
                        basisBusinessManageService.handleBasis(value.getBasisBusinessManages(), guidanceItem.getId(), account, "default");
                    } else if (value.getType() != null && value.getType().equals(2)) {
                        itemRepositoryService.update(guidanceItem);
                        value.getImgList().forEach(imgObj -> {
                            //                            有id的图片是需要删除的
                            if (imgObj.getId() != null) {
                                ImgUploadService.deleteById(imgObj.getId());
                            } else {
                                imgsService.save(guidanceItem.getId(), "GUIDEITEMIMG", imgObj.getUrl());
                            }
                        });
                        //处理依据
                        basisBusinessManageService.handleBasis(value.getBasisBusinessManages(), guidanceItem.getId(), account, "default");
                    } else if (value.getType() != null && value.getType().equals(-1)) {
                        itemRepositoryService.deleteById(value.getId());
                        ImgUploadService.deleteByBIdAndBType(value.getId(), "GUIDEITEMIMG");
                        //删除依据
                        List<BasisBusinessManage> manageList = basisBusinessManageService.getRepositoryService().findList(BasisBusinessManage.builder().businessId(value.getId()).basisType("default").build());
                        if (manageList != null) {
                            List<Long> longs = Lists.newArrayList();
                            for (BasisBusinessManage manage : manageList) {
                                longs.add(manage.getId());
                            }
                            if (longs.size() > 0) {
                                basisBusinessManageService.getRepositoryService().deleteByIds(longs);
                            }
                        }
                    }
                }
            }
            repositoryService.update(businessGuidance);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException(ResultType.UPDATE_ERROR.getReason(), ResultType.UPDATE_ERROR);
        }
        saveLog(OperationLog.OperationType.EDIT, (account.getRealName() != null ? account.getRealName() : "") + "为\"" + request.getUnit() + "\"编辑了业务指导,指导单号:" + request.getGuidanceNum());
        return Result.ok(businessGuidance.getId());
    }

    /**
     * 提交 on 2020/5/7 16:56
     *
     * @param commitRequest commitRequest
     * @return Result<?>
     */
    public Result<?> commit(CommitRequest commitRequest) {
        if (commitRequest.getId() == null) {
            return Result.body(commitRequest.getId(), ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        GuiBusinessGuidance guidance = repositoryService.getById(commitRequest.getId());
        if (guidance == null) {
            return Result.body(commitRequest.getId(), ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if (!"STAGE".equals(guidance.getState())) {
            return Result.body(guidance.getState(), ResultType.CHECK_ERROR).withMessage("只有暂存状态可以提交");
        }
        guidance.setState("WAIT_CONFIRM");
        try {
            notifyMessageScheduleTask.businessGuidanceAddNotifyMessage(guidance, commitRequest.getCopyTos());
            repositoryService.update(guidance);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(commitRequest.getId(), ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(commitRequest.getId());
    }

    /**
     * 查看业务指导 on 2020/3/12 14:45
     *
     * @param id id
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> getDetails(Long id) {
        GuiBusinessGuidance guidance = repositoryService.getById(id);
        if (guidance == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        GuiGuidanceItem guiGuidanceItem = new GuiGuidanceItem();
        guiGuidanceItem.setId(null);
        guiGuidanceItem.setCreatedAt(null);
        guiGuidanceItem.setGuidanceId(id);
        guiGuidanceItem.setDataState(1);
        guidance.setItemList(itemRepositoryService.findList(guiGuidanceItem));
        if (guidance.getItemList() != null && guidance.getItemList().size() > 0) {
            guidance.getItemList().forEach(value -> {
                Imgs imgs = new Imgs();
                imgs.setBusinessId(value.getId());
                imgs.setBusinessType("GUIDEITEMIMG");
                value.setImgList(imgsService.findList(imgs));
                //依据
                List<BasisBusinessManageRequest> requestList = Lists.newArrayList();
                List<BasisBusinessManage> manageList = basisBusinessManageService.getRepositoryService().findList(BasisBusinessManage.builder().businessId(value.getId()).basisType("default").build());
                if (manageList != null) {
                    manageList.forEach(basisValue -> {
                        BasisBusinessManageRequest request = new BasisBusinessManageRequest();
                        BeanUtils.copyProperties(basisValue, request);
                        try {
                            request.setContent(new String(basisValue.getContent(), "UTF-8"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        requestList.add(request);
                    });
                }
                value.setBasisBusinessManages(requestList);
            });
        }
        //指导员电话
        if (guidance.getInstructorId() != null) {
            Account account = accountRepositoryService.getById(guidance.getInstructorId());
            if (account != null) {
                guidance.setInstructorPhone(account.getTeleNum());
            }
        }
        return Result.ok(guidance);
    }

    /**
     * 删除业务指导 on 2020/3/12 14:44
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> delete(Long id) {
        GuiBusinessGuidance guidance = repositoryService.getById(id);
        if (guidance == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if (!"STAGE".equals(guidance.getState())) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("非暂存状态不可删除");
        }
        Account account = UserPrincipal.getCurrentUser();
        try {
            guidance.setDataState(-1);
            guidance.setRecycleDate(new Date());
            if (account != null) {
                guidance.setRecycleOpsId(account.getId());
                guidance.setRecycleOpsName(account.getRealName());
            }
            repositoryService.update(guidance);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(id, ResultType.BUSINESS_ERROR);
        }
        saveLog(OperationLog.OperationType.DELETE, "删除业务指导,指导单号:" + guidance.getGuidanceNum());
        return Result.ok(id);
    }

    /**
     * 业务指导列表
     *
     * @return Result<?>
     */
    public Result<?> findPage(GuiBusinessPageRequest request) {
        if (request.getPn() == null) {
            request.setPn(1);
        }
        if (request.getPageSize() == null) {
            request.setPageSize(30);
        }
        Account account = UserPrincipal.getCurrentUser();
        if (account != null && !"ADMIN".equals(account.getRoleName()) && !"管理员".equals(account.getRoleName())
                && !"业务指导处长".equals(account.getRoleName()) && !"正副局长".equals(account.getRoleName())
                && !"正副馆长".equals(account.getRoleName())) {
            request.setInstructorId(String.valueOf(account.getId()));
        }
        //已回复待回复
        if (request.getState() != null && (request.getState().equals("REPLIED") || request.getState().equals("NO_REPLY"))) {
            request.setReplyState(request.getState());
            request.setState(null);
        }
        PageInfo<GuiBusinessGuidance> guidancePageInfo = repositoryService.findPage(request);
        return Result.ok(guidancePageInfo);
    }

    /**
     * 用户业务指导列表
     *
     * @return Result<?>
     */
    public Result<?> userFindPage(GuiBusinessPageRequest request) {
        PageInfo<GuiBusinessGuidance> guidancePageInfo = repositoryService.userFindPage(request);
        return Result.ok(guidancePageInfo);
    }

    /**
     * 归档:归档或取消归档 on 2020/4/29 10:12
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    public ResponseEntity<?> archive(Long id) {
        GuiBusinessGuidance guidance = repositoryService.getById(id);
        if (guidance == null) {
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        if ("COMPLETE".equals(guidance.getState())) {
            guidance.setState("ARCHIVE");
            saveLog(OperationLog.OperationType.ARCHIVE, "业务指导(" + guidance.getGuidanceNum() + ")归档成功");
        } else if ("ARCHIVE".equals(guidance.getState())) {
            guidance.setState("COMPLETE");
            saveLog(OperationLog.OperationType.CANCEL_ARCHIVE, "业务指导(" + guidance.getGuidanceNum() + ")取消归档");
        }
        try {
            repositoryService.update(guidance);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误"));
        }
        return ResponseEntity.ok(Result.ok(id));
    }

    /**
     * 撤销 on 2020/4/29 10:38
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<?> revoke(Long id) {
        GuiBusinessGuidance guidance = repositoryService.getById(id);
        if (guidance == null) {
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        //改为暂存
        guidance.setState("STAGE");
        GuiGuidanceMendList mendList = mendListService.getMendListRepositoryService().getByGuidanceId(guidance.getId());
        if (mendList != null) {
            if (!mendList.getMendState().equals(1)) {
                return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("整改单已使用,不能撤销"));
            }
            //删除整改单相关
            mendListService.delete(mendList.getId());
        }
        //删除被指导签名
        if (guidance.getGuideAdviceSign() != null && !"".equals(guidance.getGuideAdviceSign())) {
            ImgUploadService.deleteById(Long.valueOf(guidance.getGuideAdviceSign()));
        }
        //删除指导签名
        if (guidance.getAdviceImgSign() != null && !"".equals(guidance.getAdviceImgSign())) {
            ImgUploadService.deleteById(Long.valueOf(guidance.getAdviceImgSign()));
        }
        guidance.setGuideAdviceSign("0");
        guidance.setAdviceImgSign("0");
        try {
            repositoryService.update(guidance);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException("操作过程中出现错误", ResultType.BUSINESS_ERROR);
        }
        saveLog(OperationLog.OperationType.CANCEL, "撤销业务指导,指导单号:" + guidance.getGuidanceNum());
        return ResponseEntity.ok(Result.ok(id));
    }

    /**
     * @Description 获取业务指导员列表
     * @params:
     * @returns:
     * @dateTime:
     */
    public List<InstructorResult> getInstructorList() {
        return repositoryService.getInstructorList();
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description   描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description) {
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "业务指导",
                OperationLog.BusinessType.BUSINESS
        ));
    }

    /**
     * @Description 获取当前指导人已上报条数
     * @params:
     * @returns:
     * @dateTime:
     */
    public Result<?> getRecorderMount(Long userId) {
        int result = 0;
        String regEx = "[^0-9]";
        String count = repositoryService.getRecorderMount(userId);
        Pattern p = Pattern.compile(regEx);
        if (count != null) {
            Matcher m = p.matcher(count);
            result = Integer.parseInt(m.replaceAll("").trim());
        }
        return Result.ok(result);
    }

    /**
     * 立档单位确认
     *
     * @param request UnitConfirmRequest
     * @return Result<?>
     */
    public Result<?> unitConfirm(UnitConfirmRequest request) {
        if (request.getId() == null) {
            return Result.body(request.getId(), ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        GuiBusinessGuidance guidance = repositoryService.getById(request.getId());
        if (guidance == null) {
            return Result.body(request.getId(), ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if (!"WAIT_CONFIRM".equals(guidance.getState())) {
            return Result.body(guidance.getState(), ResultType.CHECK_ERROR).withMessage("只有待确认状态可以进行该操作");
        }
        if (request.getGuideAdviceSign() != null) {
            guidance.setGuideAdviceSign(String.valueOf(imgsService.save(guidance.getId(), "BYGUIDESIGN", request.getGuideAdviceSign().getUrl())));
        }
        guidance.setGuidanceAdvice(request.getGuidanceAdvice());
        guidance.setState("COMPLETE");
        try {
            repositoryService.update(guidance);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(request.getId(), ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(request.getId());
    }
}